import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Table, Button, Input, Select, Form, Modal, Radio, DatePicker, Checkbox,message } from 'antd';
import dayjs from 'dayjs';
import 'antd/dist/reset.css';
import { api, queryList } from '../api/api';
import Url from '../api/url';
import { use } from 'react';


function UserPage() {
  const navigate = useNavigate();
  const [users, setUsers] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [filters, setFilters] = useState({
    CUSTOMER_NAME: '',
    USERID: '',
    CUSTOMER_TYPE: '',
    IS_CHARGEABLE: '',
    APPLICANT: '',
    VALID_UNTIL: '',
  });
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [roleForm] = Form.useForm();
  const [editingUserKey, setEditingUserKey] = useState(null);
  const [roleUserKey, setRoleUserKey] = useState(null);
  const [roleOptions, setRoleOptions] = useState([]);

 
  const pageLoad = async () => {

    const roleRes = await queryList({url:Url.getRoles})
    if(roleRes){
      setRoleOptions(roleRes.map(e=>({PK:e.PK,ROLENAME:e.ROLENAME})))
    }

  }


  useEffect(() => {
    queryUser();
    pageLoad();
  }, []);

  const queryUser = async () => {
    const userList = await queryList({url:Url.getUser,params:filters})
    setUsers(userList)
   
  };

  const columns = [
  { title: '用户名', dataIndex: 'USERID', key: 'USERID' },
  { title: '联系电话', dataIndex: 'PHONE', key: 'PHONE' },
  // { title: '客户编码', dataIndex: 'CUSTOMER_CODE', key: 'CUSTOMER_CODE' },
  { title: '客户名称', dataIndex: 'CUSTOMER_NAME', key: 'CUSTOMER_NAME' },
  { title: '客户类型', dataIndex: 'CUSTOMER_TYPE', key: 'CUSTOMER_TYPE' },
  // { title: '是否收费', dataIndex: 'IS_CHARGEABLE', key: 'IS_CHARGEABLE' },
  { title: '收费金额', dataIndex: 'CHARGE_AMOUNT', key: 'CHARGE_AMOUNT' },
  // { title: '申请人', dataIndex: 'APPLICANT', key: 'APPLICANT' },
  // { title: '显示价格', dataIndex: 'SHOW_PRICE', key: 'SHOW_PRICE' },
  { 
    title: '有效期至', 
    dataIndex: 'VALID_UNTIL', 
    key: 'VALID_UNTIL',
    render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : ''
  },{ title: '角色权限', dataIndex: 'ROLES', key: 'ROLES',render: (text, record) => {
      if (!text) return '-';
      const ids = text.split(',');
      const roleNames = ids.map(id => 
        roleOptions.find(role => role.PK.toString() === id.toString())?.ROLENAME
      ).filter(Boolean);
      return roleNames.length ? roleNames.join(', ') : '-';
    } },
  { title: '备注', dataIndex: 'REMARKSS', key: 'REMARKSS' },
  { 
    title: '更新日期', 
    dataIndex: 'UPDATETIME', 
    key: 'UPDATETIME',
    render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''
  },
  // { title: '是否活动', dataIndex: 'ISACTIVE', key: 'ISACTIVE' },
];

  const handleInputChange = (changedValues) => {
    setFilters({ ...filters, ...changedValues });
  };

  const handleAdd = () => {
    setAddModalVisible(true);
  };

  const handleAddOk = async () => {
    const user = await addForm.validateFields()
    user.VALID_UNTIL = user.VALID_UNTIL ? dayjs(user.VALID_UNTIL).format('YYYY-MM-DD') : null
    var res = await api({url:Url.addUser,data:user})
    message.success(res.msg)
    setAddModalVisible(false);
    queryUser();
   
  };



  const handleDelete = () => {
    if (selectedRowKeys.length === 0) return;
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的${selectedRowKeys.length}条用户记录吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await api({url:Url.delUser,data: {pkList:selectedRowKeys}}) 
            setUsers(users.filter(u => !selectedRowKeys.includes(u.PK)));
            setSelectedRowKeys([]);
            message.success(res.msg);
      },
    });
  };

  // 打开修改弹窗
  const handleEdit = () => {
    if (selectedRowKeys.length !== 1) {
      Modal.info({ title: '提示', content: '请选择一条要修改的数据' });
      // message.warning('请选择一条要修改的数据')
      return;
    }
    const user = users.find(u => u.PK === selectedRowKeys[0]);
    setEditingUserKey(user.PK);
    // 处理日期类型字段，带出选中数据
    editForm.setFieldsValue({
      ...user,
      VALID_UNTIL: user.VALID_UNTIL ? dayjs(user.VALID_UNTIL) : null,
    });
    setEditModalVisible(true);
  };

  // 确认修改
  const handleEditOk = async () =>  {

    const values = await editForm.validateFields()
    const updatedUser = {
        ...values,
        PK: editingUserKey,
        VALID_UNTIL: values.VALID_UNTIL ? values.VALID_UNTIL.format('YYYY-MM-DD') : '',
      };

      const res = await api({url:Url.updateUser,data:updatedUser})
      updatedUser.UPDATETIME = res.data.UPDATETIME

      setUsers(users.map(u => u.PK === editingUserKey ? updatedUser : u));
      setEditModalVisible(false);
      setSelectedRowKeys([]);
      message.success(res.msg)
  };

  // 取消修改
  const handleEditCancel = () => {
    setEditModalVisible(false);
  };

  // 打开分配角色弹窗
  const handleAssignRole = () => {
    if (selectedRowKeys.length !== 1) {
      Modal.info({ title: '提示', content: '请选择一条要分配角色的数据' });
      // message.warning('请选择一条要分配角色的数据')
      return;
    }
    const user = users.find(u => u.PK === selectedRowKeys[0]);
    setRoleUserKey(user.PK);
    // 将逗号分隔的ID字符串转为数组
    const ids = user.ROLES ? user.ROLES.split(',').map(id => Number(id)) : [];

    roleForm.setFieldsValue({ roles: ids || [] });
    setRoleModalVisible(true);
  };

  // 保存分配角色
  const handleRoleOk = async () => {
    const values = await roleForm.validateFields()
    const user = users.find(u => u.PK === selectedRowKeys[0]);
    user.ROLES = values.roles.toString()
    const res = await api({url:Url.updUserRole,data:{user:user}})
    message.success(res.msg)

    setUsers(users.map(u => u.key === roleUserKey ? { ...u, roles: values.roles } : u));
    setRoleModalVisible(false);
    setSelectedRowKeys([]);
  };
  const handleRoleCancel = () => {
    setRoleModalVisible(false);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const resetPassWord = async () => {
    if (selectedRowKeys.length !== 1) {
      Modal.info({ title: '提示', content: '请选择一条要重置密码的数据' });
      // message.warning('请选择一条要重置密码的数据')
      return;
    }

    const user = users.find(u => u.PK === selectedRowKeys[0]);
    Modal.confirm({
      title: '确认重置密码',
      content: `确定要重置${user.USERID}的密码吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await api({url:Url.resetPwd,data:user})
        message.success(res.msg)
      },
    });
  }


  return (
    <div style={{ padding: 0,background:'#f5f6fa' }}>

      <Form
        layout="inline"
        style={{ marginBottom: 16, background: '#fff', padding: 16, borderRadius: 8 }}
        initialValues={filters}
        onValuesChange={handleInputChange}
        clearOnDestroy
      >
        <Form.Item name="CUSTOMER_NAME">
          <Input placeholder="客户名称" style={{ width: 120 }} />
        </Form.Item>
        <Form.Item name="USERID">
          <Input placeholder="用户名" style={{ width: 120 }}   />
        </Form.Item>
        {/* <Form.Item name="CUSTOMER_TYPE">
          <Select placeholder="客户类型" style={{ width: 120 }} allowClear>
            <Select.Option value="个人客户">个人客户</Select.Option>
            <Select.Option value="企业客户">企业客户</Select.Option>
          </Select>
        </Form.Item> */}
        <Form.Item name="ISACTIVE">
          <Select placeholder="是否活动" style={{ width: 100 }} allowClear>
            <Select.Option value="是">是</Select.Option>
            <Select.Option value="否">否</Select.Option>
          </Select>
        </Form.Item>
        {/* <Form.Item name="VALID_UNTIL">
          <Input placeholder="有效期至" style={{ width: 120 }} />
        </Form.Item> */}
        <Form.Item>
          <Button type="primary" onClick={queryUser}>检索</Button>
        </Form.Item>
      </Form>
      <div style={{ marginBottom: 8, background: '#fff', padding: 8, borderRadius: 8 }}>
        <Button type="primary" onClick={handleAdd}>添加</Button>
        <Button danger style={{ marginLeft: 8 }} onClick={handleDelete} disabled={selectedRowKeys.length === 0}>删除</Button>
        <Button style={{ marginLeft: 8 }} onClick={handleEdit}>修改</Button>
        <Button style={{ marginLeft: 8 }} onClick={handleAssignRole}>分配角色</Button>
        <Button style={{ marginLeft: 8 }} onClick={resetPassWord} >重置密码</Button>
      </div>   
      <Table
        rowSelection={rowSelection}
        rowKey={'PK'}
        columns={columns}
        dataSource={users}
        bordered
        pagination={{ pageSize: 10 }}
        style={{ background: '#fff', borderRadius: 8 }}
        scroll={{ x: 'max-content' }}
      />
      <Modal
        title="添加"
        width={800}
        okText="保存"
        cancelText="取消"
        open={addModalVisible}
        destroyOnHidden
        onCancel={()=>setAddModalVisible(false)}
        onOk={handleAddOk}
      >
        <Form
          form={addForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 17 }}
          style={{ marginTop: 24 }}
          initialValues={{  ISACTIVE: '是' }}
          scrollToFirstError
          clearOnDestroy
        >

          <Form.Item label="用户名" name="USERID" rules={[{ required: true, message: '请输入用户名' }]}> 
            <Input /> 
          </Form.Item>
          <Form.Item label="联系电话" name="PHONE"> 
            <Input /> 
          </Form.Item>
          {/* <Form.Item label="客户编码" name="CUSTOMER_CODE"> 
            <Input /> 
          </Form.Item> */}
          <Form.Item label="客户名称" name="CUSTOMER_NAME" rules={[{ required: true, message: '请输入客户名称' }]}> 
            <Input /> 
          </Form.Item>
          <Form.Item label="客户类型" name="CUSTOMER_TYPE" > 
            <Select placeholder="请选择"> <Select.Option value="个人客户">个人客户</Select.Option> <Select.Option value="企业客户">企业客户</Select.Option> </Select> 
          </Form.Item>
          <Form.Item label="是否活动" name="ISACTIVE" > 
            <Radio.Group> <Radio value="是">是</Radio> <Radio value="否">否</Radio> </Radio.Group> 
          </Form.Item>
          <Form.Item label="收费金额" name="CHARGE_AMOUNT"> 
            <Input /> 
          </Form.Item>
          {/* <Form.Item label="申请人" name="APPLICANT"> 
            <Input /> 
          </Form.Item> */}
          {/* <Form.Item label="是否显示价格" name="showPrice"> 
            <Radio.Group> <Radio value="是">是</Radio> <Radio value="否">否</Radio> </Radio.Group> 
          </Form.Item> */}
          <Form.Item label="有效期至" name="VALID_UNTIL"> 
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" /> 
          </Form.Item>
          <Form.Item label="备注" name="REMARKS"> 
            <Input /> 
          </Form.Item>

        </Form>

      </Modal>

      <Modal
        title="修改"
        open={editModalVisible}
        onOk={handleEditOk}
        onCancel={handleEditCancel}
        okText="保存"
        cancelText="取消"
        destroyOnHidden
        width={800}
      >
        <Form
          form={editForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 17 }}
          style={{ marginTop: 24 }}
          initialValues={{  ISACTIVE: '是' }}
          clearOnDestroy
        >
          <Form.Item label="用户名" name="USERID"  rules={[{ required: true, message: '请输入用户名' }]}> 
            <Input disabled /> 
            </Form.Item>
          <Form.Item label="联系电话" name="PHONE"> 
            <Input /> 
            </Form.Item>
          {/* <Form.Item label="客户编码" name="CUSTOMER_CODE"> 
            <Input /> 
            </Form.Item> */}
          <Form.Item label="客户名称" name="CUSTOMER_NAME" rules={[{ required: true, message: '请输入客户名称' }]}> 
            <Input /> 
            </Form.Item>
          <Form.Item label="客户类型" name="CUSTOMER_TYPE" > 
            <Select placeholder="请选择"> <Select.Option value="个人客户">个人客户</Select.Option> <Select.Option value="企业客户">企业客户</Select.Option> </Select> 
            </Form.Item>
          <Form.Item label="是否活动" name="ISACTIVE" > 
            <Radio.Group> <Radio value="是">是</Radio> <Radio value="否">否</Radio> </Radio.Group> 
            </Form.Item>
          <Form.Item label="收费金额" name="CHARGE_AMOUNT"> 
            <Input /> 
          </Form.Item>
          {/* <Form.Item label="申请人" name="APPLICANT"> 
            <Input /> 
            </Form.Item> */}
          {/* <Form.Item label="是否显示价格" name="showPrice"> <Radio.Group> <Radio value="是">是</Radio> <Radio value="否">否</Radio> </Radio.Group> </Form.Item> */}
          <Form.Item label="有效期至" name="VALID_UNTIL"> 
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" /> 
            </Form.Item>
          <Form.Item label="备注" name="REMARKS"> 
            <Input /> 
            </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="用户分配角色"
        open={roleModalVisible}
        onOk={handleRoleOk}
        onCancel={handleRoleCancel}
        okText="保存"
        cancelText="取消"
        destroyOnHidden
        width={500}
        forceRender
      >
        <Form form={roleForm} labelCol={{ span: 0 }} wrapperCol={{ span: 24 }} clearOnDestroy>
          <Form.Item name="roles" > 
            <Checkbox.Group style={{ width: '100%' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24 }}>
                {roleOptions.map(role => (
                  <Checkbox key={role.PK} value={role.PK} style={{ minWidth: 120, marginBottom: 12 }}>{role.ROLENAME}</Checkbox>
                ))}
              </div>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default UserPage;